#!/usr/bin/env python2 
# -*- coding:utf-8 -*-

from flask import Blueprint

from Ump import webutil
from Ump.objs.user.manager import UserManager

from base import BaseHandler, add_manager


user_m = UserManager()


@add_manager(user_m)
class Users(BaseHandler):
    _post_params = {
        'need': [
            ('name', 'username'),
            'password',
            ('identity', 'role'),
            'quota',
            'repnum',
        ],
        'optional': [
            'protection_domain_ids',
            'chap_name',
            'chap_password'
        ],
    }

    @webutil.authenticated()
    def post(self):
        params = self.check_params()
        return webutil.web_return(user_m.create, params)


@add_manager(user_m)
class User(BaseHandler):
    _put_params = {
        'optional': [
            'quota',
            'repnum',
            'chap_name',
            'chap_password',
        ],
    }

    @webutil.authenticated()
    def delete(self, _id):
        return webutil.web_return(user_m.delete, {'id': _id})

    @webutil.authenticated()
    def put(self, _id):
        params = self.check_params()
        params.update(id=_id)
        return webutil.web_return(user_m.update, params)


@add_manager(user_m)
class Password(BaseHandler):
    _put_params = {
        'optional':[
            'password',
            'new_password',
        ]
    }

    @webutil.authenticated()
    def put(self, _id):
        params = self.check_params()
        params.update(id=_id)
        return webutil.web_return(user_m.password, params)


app = Blueprint('user', __name__, template_folder='templates')
app.add_url_rule('/user', view_func=Users.as_view('user_create'))
app.add_url_rule('/user/<int:_id>', view_func=User.as_view('user_update_and_delete'))
app.add_url_rule('/user/<int:_id>/password', view_func=Password.as_view('user_password_update'))